<template>
  <div class="top-tab" v-if="tabs.length > 1">
    <div class="top-tab-container">
      <TopTabItem
        v-for="item in tabs"
        :key="item.title"
        :tabName="item.title"
        :active="selectValueParent.title === item.title"
        :width="`${100 / tabs.length}vw`"
        @click.native="change('parent', item.title)"
      >
      </TopTabItem>
    </div>
    <template v-if="selectValueParent.subTab">
      <atom-tabs :active="selectValueChild" @click="change('child', $event)">
        <atom-tab
          v-for="_item in selectValueParent.subTab"
          :key="_item.title"
          :title="_item.title"
          :name="_item.title"
        ></atom-tab>
      </atom-tabs>
    </template>
  </div>
</template>

<script setup lang="ts">
import TopTabItem from '@/components/top/TopTabItem.vue';
import { Tab } from '@/types/home.d';
interface Props {
  value: Tab[];
}

const props = withDefaults(defineProps<Props>(), {});

interface Emits {
  (e: 'input', params: Tab[]): void;
}
const emits = defineEmits<Emits>();
// 当前底部tab选中带出的顶部tab内容
const tabs = computed(() => {
  const result = props.value.find(item => item.active);
  return result?.subTab || [];
});
// 第二级选中title
const selectValueParent = computed(() => {
  return tabs.value.find(item => item.active) || tabs.value[0];
});
// 第三级选中title
const selectValueChild = computed(() => {
  const result = tabs.value.find(item => item.active);
  const subTab = result?.subTab || [];
  return subTab.find(item => item.active)?.title || '';
});
const change = (type: 'parent' | 'child', checkedValue: string) => {
  const result = props.value.map(item => {
    let subTab = JSON.parse(JSON.stringify(item.subTab));
    if (item.active) {
      // @ts-ignore
      subTab = item.subTab.map(_item => {
        if (type === 'parent') {
          return { ..._item, active: _item.title === checkedValue };
        } else {
          return {
            ..._item,
            subTab: _item.active
              ? _item.subTab?.map(_it => ({ ..._it, active: _it.title === checkedValue }))
              : _item.subTab
          };
        }
      });
    }
    return {
      ...item,
      subTab
    };
  });
  emits('input', result);
};
</script>

<style lang="less">
.top-tab-container {
  display: flex;
  align-items: center;
}
</style>
